package com.aispeech.task.lasr;

import com.aispeech.task.common.data.domain.Task;
import com.aispeech.task.common.exceptions.TaskException;
import com.aispeech.task.common.handler.TaskHandler;
import com.aispeech.task.common.handler.TaskManager;
import com.aispeech.task.fsm.StateMachine;
import com.aispeech.task.lasr.event.InitialEvent;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class LASRTaskHandler implements TaskHandler {
    private static TaskManager manager;
    private static ExecutorService threadPool;

    public static TaskManager taskManager() {
        return manager;
    }
    public static ExecutorService threadPool() {
        return threadPool;
    }

    public static void updateTaskStatus(Task task, int progress, String metrics) throws TaskException {
        task.getMetrics().put(metrics, System.currentTimeMillis());
        manager.updateProgress(task, progress);
    }

    @Override
    public void initialize(TaskManager manager, int eventThreads) {
        LASRTaskHandler.manager = manager;
        LASRTaskHandler.threadPool = Executors.newFixedThreadPool(eventThreads);
    }

    @Override
    public void execute(Task task) throws TaskException {
        log.info("[ received ] task: {}", task);

        StateMachine<Task> stateMachine = new StateMachine<>(
                LASRState.Initial,
                new InitialEvent(task)
        );

        try {
            stateMachine.run();
        } catch (Exception e) {
            throw new TaskException(e.getMessage());
        }

        log.info("[ executed ] task: {}", task);
    }
}
